<?php

namespace cesi\plastprodBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use cesi\plastprodBundle\Entity\User;
use cesi\plastprodBundle\Entity\Game;
use cesi\plastprodBundle\Entity\Password;
use cesi\plastprodBundle\Entity\Picture;
use cesi\plastprodBundle\Form\UserType;
use cesi\plastprodBundle\Form\PasswordType;
use cesi\plastprodBundle\Form\PictureType;
use cesi\plastprodBundle\Entity\Friend;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\SecurityContext;

class UserController extends Controller {

   
    /**
     * Affichage de l'inscription.
     */
    public function displaySubscribeAction() {
        $user = new User();
        $insc = $this->createForm(new UserType(), $user);
        return $this->render('cesiplastprodBundle:User:inscription.html.twig', array('insc' => $insc->createView()));
    }

    /**
     * Contrôleur de l'inscription.
     */
    public function registerAction() {
        $user = new User(); // Création de l'utilisateur.
        $request = $this->getRequest(); // Récupération de la requête/
        $insc = $this->createForm(new UserType(), $user);
        $insc->bindRequest($request);
        $data = $insc->getData();
        $em = $this->getdoctrine()->getEntityManager();
        $u = $em->getRepository('cesiplastprodBundle:User')->findBy(array('user_login' => $data->getUserLogin()));

        /*
         * On vérifie que la requête est bien une requête POST.
         * Et que le mot de passe et la confirmation sont identiques.
         */


        if ($data->getUserLogin() != "" && $data->getUserMail() != "" && $data->getUserPassword() != "") {
            if ($request->getMethod() == 'POST' && $u == null) {

                if ($data->getUserPassword() == $request->get('cmdp')) {
                    if (preg_match('`^\w{4,16}$`', $data->getUserLogin()) &&
                            preg_match('`^\w{4,16}$`', $data->getUserPassword()) &&
                            preg_match('`^\w{4,16}$`', $request->get('cmdp'))) {
                        $user->setUserLogin($data->getUserLogin());
                        $user->setUserPassword($data->getUserPassword());
                    } else {
                        return new Response('Le nom d\'utilisateur et le mot de passe doivent contenir entre 4 et 16 caractères alphanumériques');
                    }
                    if (preg_match("[^([a-zA-Z0-9]+(([\.\-\_]?[a-zA-Z0-9]+)+)?)\@(([a-zA-Z0-9]+[\.\-\_])+[a-zA-Z]{2,4})$]", $data->getUserMail())) {
                        $user->setUserMail($data->getUserMail());
                    } else {
                        return new Response('L\'email n\'est pas un email valide');
                    }
                    $user->setSalt(md5(time()));
                    $user->setUserStatus("1");
                    $user->setUserSubscribeDate(new \DateTime());
                    $user->setUserFirstName($data->getUserFirstName());
                    $user->setUserLastname($data->getUserLastname());
                     $factory = $this->container->get('security.encoder_factory');
                    $encoder = $factory->getEncoder($user);
                    $password = $encoder->encodePassword($user->getUserPassword(), $user->getSalt());
                    $user->setUserPassword($password);
                    $em = $this->getDoctrine()->getEntityManager();
                    $em->persist($user);
                    $em->flush();
                    return new Response('OK');
                }
                return new Response('Le mot de passe et sa confirmation ne correspondent pas');
            }
            return new Response('L\'utilisateur existe déjà');
        }
        return new Response('Tous les champs sont obligatoires');
    }

    /**
     * Contrôleur du profil.
     */
    public function profilAction() {
        $em = $this->getDoctrine()
                   ->getEntityManager();
        
		$user = $this->get('security.context')->getToken()->getUser();
        if(is_object($user)){
            if($user->getUserStatus() == 0){
                return $this->render('cesiplastprodBundle:User:index.html.twig');
            }
            $log = $user->getUserLogin();
            $email = $user->getUserMail();
            $subdate = $user->getUserSubscribeDate();
            $fname = $user->getUserFirstName();
            $lname = $user->getUserLastname();
            
             $password = new Password();
            $passwordForm = $this->createForm(new PasswordType(), $password);
            $avatarForm = $this->createForm(new PictureType(), $avatar);
            
            return $this->render('OweimMainBundle:User:profil.html.twig', array(
			    'log' => $log,
			    'pass' => $passwordForm->createView(),
                'avatar' => $avatarForm->createView(),
                'mail' => $email,
                'subdate' => $subdate,
                'fname' => $fname,
                'lname' => $lname,
                 ));
        }else{
            return $this->render('cesiplastprodBundle:User:displaySubscribe.html.twig');
        }
    }

    public function deleteAccountAction() {
        $user = $this->get("security.context")->getToken()->getUser();
        $response = new Response('OK');
        // session invalidation
        $this->get('request')->getSession()->invalidate();

        $request = $this->getRequest();
        // OR cookie invalidation
        foreach ($request->cookies as $cookieName => $cookieData) {
            $response->headers->clearCookie($cookieName, $cookieData['path'], $cookieData['domain']);
        }

        $this->get('security.context')->setToken(null);

        if ($request->isXmlHttpRequest()) {

            $user->setUserStatus('0');
        }
        return $response;
    }

}

